const {
  $Toast
} = require('../../utils/iview/base/index');
const Tools = require('../../utils/modules/Tools');
import NetWork from '../../utils/modules/NetWork';

const app = getApp();

var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({
  data: {
    province: '',
    page: 1,
    city: '',
    banner: null,
    student: null,
    shopList: null,
    shopname: [],
    vehicle: [],
    auth: true,
    isloade: {
      hidden: false
    },
    _baseUrl: app.globalData._baseUrl,
    list: [],
    goods: [],
    key: app.globalData._key,
    _imgPath: app.globalData._imgPath,
    address: '',
    latitude: 23.099994,
    longitude: 113.324520,

    markers: [{
      id: 1,
      latitude: 23.099994,
      longitude: 113.324520,
      iconPath: '../../images/location.png',
      name: 'T.I.T 创意园'
    }],

  },

  
  onLoad(options) {
    var _that = this;
    // scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    const scene = decodeURIComponent(options.scene)
    console.log(scene, "options");
    qqmapsdk = new QQMapWX({
      key: _that.data.key //这里自己的key秘钥进行填充
    });
    _that.setTitle('凤鸟归巢洗车服务'); 
    _that.address();
  },


  onShow: function() {
    let _that = this;
    
    _that.getShop();
   

    //3.这里需要增加每次刷新  接口写在那就是那个的最外层,调用函数
    

    
    _that.isUserInfo();
  },

  bindshop(e) {
    wx.navigateTo({
      url: '../shop/shop?id=' + e.currentTarget.dataset.id,
    })


    //因为这个地址不是在后台数据获取的所以不会用到下面注释的代码，他是随着index页面的定位地址决定的和personal.js不一样
    // _that.setData({
    //   user: res.data.data
    // })
    //点击相对应的店铺的时候把位置地址存储起来，所以存储地址在这个位置上写
    //在代码中的店铺列表点击相对应的店铺就会有相对应的地址显示出来，是代码中bindtap="bindshop"实现的，所以要在js文件中bindshop写 
    var {
      latitude,
      longitude,
      province,
      city,
      district,
      address
    } = this.data;
    var address = {
      latitude: latitude,
      longitude: longitude,
      province: province,
      city: city,
      district: district,
      address: address
    };
    wx.setStorageSync("usreAdd", address)
    console.log(address, "157")
  },


  // dd
  intoMap: function(e) {
    var _that = this;
    wx.chooseLocation({
      success(res) {
        qqmapsdk.reverseGeocoder({ //逆地址解析
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: (res1) => {
            let res = res1.result
            console.log(res,"123");
            console.log('逆地址解析r?es===', res)
            setTimeout(()=>{
              _that.setData({
                latitude: res.location.lat,
                longitude: res.location.lng,
                address: res.address,
                markers: [{
                  id: 1,
                  width: 25,
                  height: 25,
                  iconPath: '../../images/location.png',
                  longitude: res.location.lng,
                  latitude: res.location.lat,
                  address: res.address,
                
                }],
                chooseRecommend: res.formatted_addresses.recommend
              })
            

            }, 500)

         

          }

        
        })

      }
    })

  },



  regionChange(e) {
    let that = this;
    // console.log('视野发生变化时触发===', that)
    that.mpCtx = wx.createMapContext("myMap");
    that.mpCtx.getScale({ //获取当前地图的缩放级别
      success: (res) => {
        // console.log('地图缩放级别', res.scale)
        that.mpCtx.getCenterLocation({ //获取当前地图中心的经纬度。返回的是 gcj02 坐标系
          success: (res) => {
            console.log(res.longitude)
            that.setData({
              markers: [{
                id: 1,
                width: 20,
                height: 20,
                iconPath: '../../images/location2.png',
                longitude: res.longitude,
                latitude: res.latitude,
                address: res.address
              }],
            }, () => {
              console.log(1);
              
            })
          }
        })
      },
      fail: function() {
        console.log('获取当前地图的缩放级别失败===')
      }
    })

  },

  mapend(e){
    var that = this;
    setTimeout(()=>{
      qqmapsdk.reverseGeocoder({ //逆地址解析
        location: {
          latitude: this.data.markers[0].latitude,
          longitude: this.data.markers[0].longitude
        },  
        success: (res1) => {
          let res = res1.result
          console.log('逆地址解析res===', res)
          that.setData({
            latitude: res.location.lat,
            longitude: res.location.lng,
            address: res.address,
            chooseRecommend: res.formatted_addresses.recommend,
          
            
          })

          setTimeout(()=>{
           
            that.getShop();
          },1000)
        
        }
      })
    }, 1000)
  },

  // 视野发生变化时触发
  // regionChange(e) {
  //   let that = this;
  //   // console.log('视野发生变化时触发===', that)
  //   that.mpCtx = wx.createMapContext("myMap");
  //   that.mpCtx.getScale({  //获取当前地图的缩放级别
  //     success: (res) => {
  //       // console.log('地图缩放级别', res.scale)
  //       that.mpCtx.getCenterLocation({//获取当前地图中心的经纬度。返回的是 gcj02 坐标系
  //         success: (res) => {
  //           that.setData({
  //             markers: [{
  //               id: 1,
  //               width: 15,
  //               height: 20,
  //               iconPath: '../../images/location.png',
  //               longitude: res.longitude,
  //               latitude: res.latitude,
  //               address: res.address
  //             }],
  //           }, () => {
  //             qqmapsdk.reverseGeocoder({  //逆地址解析
  //               location: {
  //                 latitude: res.latitude,
  //                 longitude: res.longitude
  //               },
  //               success: (res1) => {
  //                 let res = res1.result
  //                 // console.log('逆地址解析res===', res)
  //                 that.setData({
  //                   latitude: res.location.lat,
  //                   longitude: res.location.lng,
  //                   address: res.address,
  //                   chooseRecommend: res.formatted_addresses.recommend
  //                 })
  //               }
  //             })
  //           })
  //         }
  //       })
  //     },
  //     fail: function () {
  //       console.log('获取当前地图的缩放级别失败===')
  //     }
  //   })
  // },

  //获取门店
  getShop() {
    let _that = this;
    let page = _that.data.page;
    
    // var token = wx.getStorageSync('token');
    // if (!token) {
    //   return;
    // }
    //1.在data里面增加完后台字段后需要给它赋值并且在外部也就是这边声明字段
    var {
      longitude,
      latitude,
    } = _that.data;
    //相同于 var latitude = _that.data.latitude;
    let net = new NetWork(_that.data._baseUrl)
    net._request({

      //对应后台的API
      url: 'api/v1/order/nearby_store',
      data: {
        //后台有多少字段就弄多少，每个都需要赋值
        page: page,
        // token: token,
        slat: latitude,
        slng: longitude,

      },

      method: 'POST'
    }, '', res => {
    
      if (page == 1) {
        _that.setData({
          vehicle: []
        })
      }
      var vehicle = this.data.vehicle.concat(res.data.data)
      _that.setData({
        vehicle: vehicle
      })
    }, res => {
      // if (res.data.error_code == 400 && res.data.msg == 'token无效或已过期') {
      //   app.refreshtoken(token);
      //   setTimeout(() => {
      //     _that.getShop();
      //   }, 1500)
      // }
    });
  },


  /* 拨打电话 */
  telPhone() {
    var that = this;
    wx.makePhoneCall({
      phoneNumber: ''
    }, res => {

    });
  },

  onReady: function(e) {
    this.mapCtx = wx.createMapContext('myMap')
  },
  getCenterLocation: function() {
    var that = this;
    that.mapCtx.getCenterLocation({
      success: function(res) {
        that.getLocal(res.latitude, res.longitude);
        that.translateMarker(res.latitude, res.longitude)
      }
    })
  },
  moveToLocation: function() {
    this.mapCtx.moveToLocation()
  },

  translateMarker: function(latitude, longitude) {
    this.mapCtx.translateMarker({
      markerId: 1,
      autoRotate: true,
      duration: 1000,
      destination: {
        latitude: latitude,
        longitude: longitude,
      },
      animationEnd() {
        console.log('animation end')
      }
    })
  },

  includePoints: function() {
    this.mapCtx.includePoints({
      padding: [10],
      points: [{
        latitude: 23.10229,
        longitude: 113.3345211,
      }, {
        latitude: 23.00229,
        longitude: 113.3345211,
      }]
    })
  },

  
  /* 修改头部标题 */
  setTitle(str) {
    wx.setNavigationBarTitle({
      title: str,
      success: function() {

      }
    })
  },

  onShareAppMessage(str) {
    return {
      title: str,
      path: this.route
    }
  },

  address() {
    // 获取当前的地理位置
    var _that = this;
    wx.getLocation({
      type: 'gcj02', //
      dataType: "json",
      success: function(res) {
        // 将当前地理位置信息保存在本地缓存中
        wx.setStorage({
          key: "gps",
          data: {
            lat: res.latitude,
            lng: res.longitude
          }
        })
        // 调用接口
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function(res) {
            let province = res.result.ad_info.province;
            let city = res.result.ad_info.city;
            let district = res.result.ad_info.district;
            let street = res.result.ad_info.street;
            let street_number = res.result.ad_info.street_number;
            let location = res.result.location;
            wx.setStorageSync('location', res.result.ad_info)
            _that.setData({
              province: province,
              city: city,
              district: district,
              street: street,
              street_number: street_number,
              latitude: location.lat,
              longitude: location.lng,
              address: res.result.address
            })

          
            _that.getShop();


            console.log(province, "province")
            console.log(city, "city")
            console.log(district, "district")
            console.log(city, "street")
            console.log(district, "street_number")
            console.log(res.result.address, "天府路")
          },

          
          

          fail: function(res) {
            console.log(res, "res");
          },
          complete: function(res) {

          }
        })
      }
    })
     

  },


  /* 隐藏分享功能 */
  hideShare() {
    wx.hideShareMenu()
  },
  /* 分享功能 */
  showShare() {
    wx.showShareMenu()
  },
  /* 下拉刷新触发功能 */
  onPullDownRefresh() {
    // 下拉刷新事件
    // wx.startPullDownRefresh
    // wx.stopPullDownRefresh
    setTimeout(() => {
      wx.stopPullDownRefresh()
      console.log('触发下拉事件');
    }, 1000)

  },

  /* 开启上拉到底部触发功能 */
  startDonwEven() {
    wx.startPullDownRefresh()
  },
  /* 停止上拉到底部触发功能 */
  stopDownEven() {
    wx.stopPullDownRefresh()
  },
  onReachBottom() {
    console.log("xiala")
    var page = this.data.page;
    this.setData({
      page: page + 1
    })
    this.getShop();


    // 上拉触底事件
    //console.log('触发触底事件')
  },

  onPageScroll(res) {
    // 页面滚动事件
    //console.log(res.scrollTop)
  },

  isUserInfo() {
    var _that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          _that.setData({
            auth: false
          })
        } else {
          _that.setData({
            auth: true
          })
        }
      }
    })
  },

  userInfo(e) {
    let _userInfo = e.detail.userInfo;
    let net = new NetWork(app.globalData._baseUrl);
    var _that = this;

    if (_userInfo) {
      this.setData({
        auth: true
      })
    }
    var {
      signature,
      rawData,
      iv,
      encryptedData
    } = e.detail;


    wx.login({
      success(res) {
        // console.log('小程序登录信息', res)
        if (res.code) {
          net._request({
            url: 'api/v1/member/wxlogin',
            method: 'POST',
            data: {
              code: res.code,
              signature: signature,
              rawData: rawData,
              iv: iv,
              encryptedData: encryptedData
            },
          }, false, sres => {
            if (sres.data.error_code == 0) {

              var _data = sres.data.data;


              // var _data = sres.data.data;
              wx.setStorageSync("user", _data.user)

              // wx.setStorageSync("token", _data.access_token)
              _that.getShop()
              // _that.setData({
              //   token: _data.access_token
              // })

            }
          });
        }
      }
    })



  }


})